package initdb

import (
	"encoding/json"
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	baseInitdb "gitee.com/zaiqiang231/go-base-app/base_app/store/initdb"
	"gitee.com/zaiqiang231/zcamp-service-camp/app/model"
	"github.com/mozillazg/go-pinyin"
	"io/ioutil"
	"net/http"
	"strings"
)

type initDistrict struct {
	baseInitdb.DbTable[model.District]
}

func (i initDistrict) GetTable() baseStore.TableInterface {
	return model.District{}
}

func (i initDistrict) InitData(ds *baseStore.Datastore) {
	//获取区域划分数据
	req, err := http.NewRequest("GET", "https://restapi.amap.com/v3/config/district?key=f0243dda7dcad83a6d164fb86705a450&subdistrict=3&extensions=base", nil)
	if err != nil {
		baseLog.Errorf("initDistrict err:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		baseLog.Errorf("initDistrict err:", err)
		return
	}
	defer res.Body.Close()
	//得到返回结果
	body, _ := ioutil.ReadAll(res.Body)
	bodystr := string(body)
	//对返回的json数据做解析
	var datajson map[string]interface{}
	err = json.Unmarshal([]byte(bodystr), &datajson)
	if err != nil {
		baseLog.Errorf("initDistrict err:", err)
		return
	}

	if datajson["districts"] != nil {
		countries := datajson["districts"].([]interface{})
		if len(countries) > 0 {
			for _, d := range countries {
				dm := d.(map[string]interface{})
				if dm["level"] == "country" && dm["adcode"] == "100000" {
					pinyinInstance := pinyin.NewArgs()
					insertData(ds, &pinyinInstance, nil, dm["districts"].([]interface{}))
				}
			}
		}
	}
}

func insertData(ds *baseStore.Datastore, pinyinInstance *pinyin.Args, parent *model.District, children []interface{}) {
	if len(children) > 0 {
		for _, c := range children {
			cm := c.(map[string]interface{})
			item := model.District{
				Status: model.DataStatusOnline,
				Name:   cm["name"].(string),
				Level:  cm["level"].(string),
				AdCode: cm["adcode"].(string),
				Center: cm["center"].(string),
				Sort:   0,
			}

			rows := pinyin.Pinyin(item.Name, *pinyinInstance)
			item.CapitalLetter = strings.ToUpper(rows[0][0][0:1])

			if parent != nil {
				item.BelongId = parent.ID
				item.Deep = parent.Deep + 1
			}
			err := ds.DB.Create(&item).Error
			if err != nil {
				baseLog.Errorf("initDistrict insert fail, %v", err)
				continue
			}
			insertData(ds, pinyinInstance, &item, cm["districts"].([]interface{}))
		}
	}
}
